function [C] = knn2nic(idx,wet)
%KNN2INC Build a directed graph based on the k nearest neighbors
%   C = KNN2INC(IDX) returns a sparse matrix
%
%
%   Suqi Liu, 05.13.2014
[n,k] = size(idx);
ivec = repmat((1:n)',k,1);
nvec = reshape(idx,[],1);
wvec = reshape(wet,[],1);
evec = repmat((1:(n*k))',2,1);
if (nargin == 1)
    B = sparse(evec,[ivec;nvec],[ones(n*k,1);-ones(n*k,1)]);
    SB = sqrt(sum(B.*B))';
    ow = repmat(SB,k,1);
    iw = SB(nvec);
    C = sparse(evec,[ivec;nvec],[1./ow;-wvec./iw]);
else
    wvec = reshape(wet,[],1);
    B = sparse(evec,[ivec;nvec],[ones(n*k,1);-wvec]);
    SB = sqrt(sum(B.*B))';
    ow = repmat(SB,k,1);
    iw = SB(nvec);
    C = sparse(evec,[ivec;nvec],[1./ow;-wvec./iw]);
end
end